package com.xiaoluo.lottery.dao;

import com.xiaoluo.lottery.entity.Round;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Component;

import java.sql.*;

/**
 * Created by Caedmon on 2016/4/5.
 */
@Component
public class RoundJdbcDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    private static final Logger log= LoggerFactory.getLogger(RoundJdbcDao.class);
    private RowMapper<Round> rowMapper =new RowMapper<Round>() {
        @Override
        public Round mapRow(ResultSet resultSet, int i) throws SQLException {
            Round round=new Round();
            round.setId(resultSet.getLong("id"));
            round.setCreatePlayerOpenId(resultSet.getString("create_player_open_id"));
            round.setCreateAt(resultSet.getTimestamp("create_at"));
            round.setGameType(resultSet.getInt("game_type"));
            round.setSingleAmount(resultSet.getDouble("single_amount"));
            round.setNum(resultSet.getInt("num"));
            round.setWinnerOpenId(resultSet.getString("winner_open_id"));
            round.setWinnerNo(resultSet.getString("winner_no"));
            round.setLotteryTime(resultSet.getTimestamp("lottery_time"));
            round.setExpiredTime(resultSet.getTimestamp("expired_time"));
            round.setStatus(resultSet.getInt("status"));
            round.setAwardTime(resultSet.getTimestamp("award_time"));
            round.setAwardFailReason(resultSet.getString("award_fail_reason"));
            round.setName(resultSet.getString("name"));
            round.setRemainNum(resultSet.getInt("remain_num"));
            return round;
        }
    };
    /**
     * 初始字段只有create_player_open_id,create_at,type,single_amount,num,expired_time
     * */
    public int insert( final Round round){
        final String sql="INSERT INTO lottery_round (name,create_player_open_id,create_at,game_type,single_amount,num,expired_time,status,item_id,remain_num) " +
                " VALUES (?,?,?,?,?,?,?,?,?,?)";
        KeyHolder keyHolder=new GeneratedKeyHolder();
        int i=jdbcTemplate.update(new PreparedStatementCreator() {
            @Override
            public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                PreparedStatement ps = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
                ps.setObject(1,round.getName());
                ps.setObject(2,round.getCreatePlayerOpenId());
                ps.setObject(3,round.getCreateAt());
                ps.setObject(4,round.getGameType());
                ps.setObject(5,round.getSingleAmount());
                ps.setObject(6,round.getNum());
                ps.setObject(7,round.getExpiredTime());
                ps.setObject(8,round.getStatus());
                ps.setObject(9,round.getItemId());
                ps.setObject(10,round.getRemainNum());
                return ps;
            }
        },keyHolder);
        long id=keyHolder.getKey().longValue();
        round.setId(id);
        return i;
    }
    public Round get(long roundId){
        String sql="SELECT * FROM lottery_round WHERE  id="+roundId;
        try{
            return jdbcTemplate.queryForObject(sql,rowMapper);
        }catch (EmptyResultDataAccessException e){
            e.printStackTrace();
            log.error("Get empty round:roundId={}",roundId);
            return null;
        }

    }
    /**
     * 可变更字段只有winner_open_id,lottery_time,status,award_time,award_fail_reason
     **/
    public int update(Round round){
        String sql="UPDATE lottery_round set winner_open_id=?,winner_no=?,lottery_time=?,status=?,award_time=?,award_fail_reason=?,remain_num=? " +
                "where id=?" ;
        Object[] params=new Object[]{
          round.getWinnerOpenId(),round.getWinnerNo(),round.getLotteryTime(),round.getStatus(),
                round.getAwardTime(),round.getAwardFailReason(),round.getRemainNum(),round.getId()
        };
        return jdbcTemplate.update(sql,params);
    }
}
